#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import logging

from google.appengine.ext import webapp
from google.appengine.ext.webapp import util

from globals import *
from models import *


# ---=== Handlers ===---

# Main Handler
class MainHandler(webapp.RequestHandler):
    def get(self):
        cats  = Category.gql('order by sort desc')
        sites = Site.gql('order by sort desc')
        result = []
        temp   = {}
        for cat in cats:
            temp[cat.name] = {'cat': cat, 'sites': []}
            result.append(temp[cat.name])
        for site in sites:
            temp[site.cat.name]['sites'].append(site)
        data = {'result': result}
        self.response.out.write(render('index', data))

# Manager Handler
class ManagerHandler(webapp.RequestHandler):
    def get(self):
        # init
        data = {'catFlag': 'Add', 'siteFlag': 'Add',
                'catForm': CategoryForm(),
                'siteForm': SiteForm()}
        logging.warning('asdf')
        
        # edit
        _act = self.request.get('act')
        if(_act == 'editcat'):
            cat = db.get(self.request.get('key'))
            #cat = Category.get_by_id(int(self.request.get('key')))
            data['cat'] = cat
            data['catFlag'] = 'Edit'
            
        elif(_act == 'editsite'):
            site = db.get(self.request.get('key'))
            data['site'] = site
            data['siteFlag'] = 'Edit'
            
        elif(_act == 'delcat'):
            cat = self.request.get('key')
            sites = Site.gql('where cat = :1', db.Key(cat))
            db.delete(sites)
            db.delete(cat)
            mem.set('_rm', 'The Category is deleted.')
            self.redirect('/manager')
            
        elif(_act == 'delsite'):
            db.delete(self.request.get('key'))
            mem.set('_rm', 'The Site is deleted.')
            self.redirect('/manager')
            
        else:
            pass
        
        # get data
        cats  = Category.gql('order by sort desc')
        if(_act == 'editcat'):
            sites = Site.gql('where cat = :1 order by sort desc', cat)
        else:
            sites = Site.gql('order by sort desc')
        data['sites'] = sites
        data['cats'] = cats
        data['return_msg'] = mem.get('_rm')
        # render
        self.response.out.write(render('manager', data))
        # clear return message
        mem.delete('_rm')
    
    def post(self):
        _act = self.request.get('act')
        if(_act == 'savecat'):
            if(self.request.get('key')):
                cat = db.get(self.request.get('key'))
            else:
                cat = Category()
            cat.name = self.request.get('name').strip()
            cat.sort = int(self.request.get('sort') or 0)
            if(cat.name == ''):
                mem.set('_rm', 'Please input Category Name.')
            else:
                cat.put()
            
        elif(_act == 'savesite'):
            if(self.request.get('key')):
                site = db.get(self.request.get('key'))
            else:
                site = Site()
            
            cat   = self.request.get('cat')
            title = self.request.get('title').strip()
            url   = self.request.get('url').strip()
            if(cat == '0'):
                mem.set('_rm', 'Please select a Category.')
            elif(title == ''):
                mem.set('_rm', 'Please input Site title.')
            elif(url == ''):
                mem.set('_rm', 'Please input Site url.')
            else:
                if(url.find('http://') == -1 and url.find('https://') == -1):
                    url = 'http://' + url
                site.cat   = db.Key(cat)
                site.title = title
                site.url   = db.Link(url)
                site.sort  = int(self.request.get('sort') or 0)
                site.put()
        else:
            pass
            
        self.redirect('/manager')





# ---=== intro ===---
def main():
    application = webapp.WSGIApplication([
        ('/manager', ManagerHandler),
        ('/',        MainHandler)
        ], debug=True)
    util.run_wsgi_app(application)

if __name__ == '__main__':
    main()
